<template>
    <div class="page-content">

        <el-row justify="space-between" :gutter="5">
            <el-col :lg="6" :md="6" :sm="14" :xs="16">
                <el-date-picker
                    v-model="timeVal"
                    type="datetimerange"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    :default-time="defaultTime1"
                />
            </el-col>
            <el-col :lg="1" :md="2" :sm="10" :xs="6">
                <el-button @click="fetchFlowData()">搜索</el-button>
            </el-col>

            <el-col :lg="10" >
                <div class="custom-segmented">
                    <el-segmented v-model="timeVal" :options="options" />
                </div>
            </el-col>
            <el-col :lg="5" :md="6" :sm="10" :xs="6" style="display: flex; justify-content: end">
                <div class="custom-css">
                <el-segmented v-model="baseVal" :options="baseNum" />
                </div>
            </el-col>
        </el-row>


        <el-row :gutter="20" style="margin-top:30px;">
            <el-col :xs="24" :sm="24" :md="24">
                <div class="tubiao">
                    <flow-rate-chart :chart-data="chartData" height="400px" bottomTextSize=12 titleTextSize=18
                        :title="chartData.node_name" :baseUnit=baseVal />
                </div>
            </el-col>
            <template v-if="ids.length > 0">
                <el-divider content-position="left">包含对象节点图</el-divider>
                <el-col v-for="(portData, index) in portChartData" :key="index" :xs="24" :sm="12" :md="12">
                    <div class="tubiao">
                        <flow-rate-chart :chart-data="portData" height="300px" :title="portData.switch_name" :baseUnit="baseVal" />
                    </div>
                </el-col>
            </template>

            
        </el-row>
    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import FlowRateChart from '@/components/Widgets/Charts/FlowRateChart.vue'
import { getNodeFlow } from '@/api/nodeFlowApi'
import { useRoute } from 'vue-router'
import {  getTreeNode} from '@/api/treeNodeApi'
import { getSwitchPortFlow } from '@/api/switchPortFlowApi'



const route = useRoute()

// 时间选择器选项
const options = ['最近24小时', '今天', '最近七天', '本周', '上周', '本月（截止当前）', '本月（完整月份）']
// 默认选择最近24小时
const timeVal = ref('最近24小时')
// 流量单位选择（1000进制或1024进制）
const baseVal = ref('1000')
const baseNum = ['1000', '1024']
// 时间选择器默认时间
const defaultTime1 = new Date(2000, 1, 1, 0, 0, 0)

// 从路由中获取节点ID
const nodeId = ref(Number(route.path.split('/').pop()) || 0)

// 初始化图表数据
const chartData = ref({})

// 初始化包含节点的ids
const ids = ref([]) // 新增响应式数组

// 初始化端口流量图表数据
const portChartData = ref([])

/**
 * 根据选择的时间选项计算具体的时间范围
 * @param timeOption - 时间选项，如'最近24小时'、'今天'等
 * @returns {{start: number, end: number}} 开始和结束时间戳（秒）
 */
const getTimeRange = (timeOption) => {
    const now = new Date()
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
    
    switch (timeOption) {
        case '最近24小时':
            return {
                start: Math.floor((now.getTime() - 24 * 60 * 60 * 1000) / 1000),
                end: Math.floor(now.getTime() / 1000)
            }
        case '今天':
            return {
                start: Math.floor(today.getTime() / 1000),
                end: Math.floor(now.getTime() / 1000)
            }
        case '最近七天':
            return {
                start: Math.floor((now.getTime() - 7 * 24 * 60 * 60 * 1000) / 1000),
                end: Math.floor(now.getTime() / 1000)
            }
        case '本周':
            const thisWeekStart = new Date(today)
            thisWeekStart.setDate(today.getDate() - today.getDay())
            return {
                start: Math.floor(thisWeekStart.getTime() / 1000),
                end: Math.floor(now.getTime() / 1000)
            }
        case '上周':
            const lastWeekStart = new Date(today)
            lastWeekStart.setDate(today.getDate() - today.getDay() - 7)
            const lastWeekEnd = new Date(today)
            lastWeekEnd.setDate(today.getDate() - today.getDay() - 1)
            return {
                start: Math.floor(lastWeekStart.getTime() / 1000),
                end: Math.floor(lastWeekEnd.getTime() / 1000)
            }
        case '本月（截止当前）':
            return {
                start: Math.floor(new Date(now.getFullYear(), now.getMonth(), 1).getTime() / 1000),
                end: Math.floor(now.getTime() / 1000)
            }
        case '本月（完整月份）':
            return {
                start: Math.floor(new Date(now.getFullYear(), now.getMonth(), 1).getTime() / 1000),
                end: Math.floor(new Date(now.getFullYear(), now.getMonth() + 1, 0).getTime() / 1000)
            }
        default:
            // 处理日期选择器的时间范围
            const [startDate, endDate] = timeVal.value;
            return {
                start: Math.floor(startDate.getTime() / 1000),
                end: Math.floor(endDate.getTime() / 1000)
            }
    }
}

/**
 * 获取节点流量数据
 * 根据当前选择的时间范围获取流量数据并更新图表
 */
const fetchFlowData = async () => {
    try {
        // 获取时间范围
        const timeRange = getTimeRange(timeVal.value)
        // 调用API获取流量数据
        const response = await getNodeFlow(nodeId.value, timeRange.start, timeRange.end)
        // 更新图表数据
        if (response.data) {
            chartData.value.items = response.data
            chartData.value.node_name = response.node_name
            chartData.value.time_start = response.time_start
            chartData.value.time_end = response.time_end

            // 获取节点的ids
            const res = await getTreeNode(nodeId.value)
            if (res.code==200) {
                
               ids.value = res.data.port_ids ? res.data.port_ids.split(','): []
               // 清空之前的端口数据
               portChartData.value = []
               // 循环ids数组，获取每个id的流量数据
               for (let i = 0; i < ids.value.length; i++) {
                   const id = ids.value[i]
                   const response = await getSwitchPortFlow(id, timeRange.start, timeRange.end)
                   if (response.data) {
                       portChartData.value.push({
                           items: response.data,
                           switch_name: response.switch_name+'-'+response.port_name,
                           time_start: response.time_start,
                           time_end: response.time_end
                       })
                   }
               }
            }
        }
    } catch (error) {
        console.error('获取流量数据失败:', error)
        // 这里可以添加错误提示
    }
}

// 监听时间选择变化
watch(timeVal, () => {
    fetchFlowData()
})

// 监听进制选择变化
watch(baseVal, () => {
    fetchFlowData()
})

// 组件挂载时获取初始数据
onMounted(() => {
    fetchFlowData()
})
</script>

<style scoped>
.page-content {
    width: 100%;
    height: 100%;
    padding: 20px;
}

.custom-segmented .el-segmented {
    height: 40px;
    padding: 6px;
    font-size: 12px;
    --el-border-radius-base: 8px;
}
.custom-css .el-segmented {
    --el-border-radius-base: 8px;
    --el-segmented-item-selected-bg-color: red;
    padding: 4px;
}


.chart-container {
    width: 100%;
    height: 300px;
}

</style>